package com.zhiwei.version.service.impl;

import com.zhiwei.common.dto.PageDataDto;
import com.zhiwei.common.util.BeanConverterUtil;
import com.zhiwei.common.util.SqlUtil;
import com.zhiwei.version.dao.entity.Config;
import com.zhiwei.version.dao.entity.ConfigExample;
import com.zhiwei.version.dao.mapper.ConfigMapper;
import com.zhiwei.version.dao.mapper.extmapper.ExtConfigMapper;
import com.zhiwei.version.dto.ConfigDto;
import com.zhiwei.version.dto.ConfigQueryDto;
import com.zhiwei.version.service.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * function
 * author zhiwei.yang
 * time 2020-3-14-14:57
 */
@Service
@Slf4j
public class ConfigServiceImpl implements ConfigService {

    @Autowired
    private ConfigMapper configMapper;
    @Autowired
    private ExtConfigMapper extConfigMapper;

    @Override
    public PageDataDto<ConfigDto> queryByPage(ConfigQueryDto configQueryDto) {
        ConfigExample configExample = new ConfigExample();
        ConfigExample.Criteria criteria = configExample.createCriteria();
        if(StringUtils.isNotEmpty(configQueryDto.getPname())){
            criteria.andPnameLike(SqlUtil.getLikeSplit(configQueryDto.getPname()));
        }
        if(null != configQueryDto.getBuildType()){
            criteria.andBuildTypeEqualTo(configQueryDto.getBuildType().shortValue());
        }
        if(null != configQueryDto.getBusiType()){
            criteria.andBuildTypeEqualTo(configQueryDto.getBusiType().shortValue());
        }
        if(null != configQueryDto.getEnableFlag()){
            criteria.andEnableFlagEqualTo(configQueryDto.getEnableFlag().shortValue());
        }
        int total = configMapper.countByExample(configExample);
        PageDataDto<ConfigDto> pageDataDto = new PageDataDto<>();
        pageDataDto.setRowCount(total);
        pageDataDto.setPageNow(configQueryDto.getPageNow());
        pageDataDto.setPageCount(total % configQueryDto.getPageSize() == 0 ? total / configQueryDto.getPageSize() :
                total / configQueryDto.getPageSize() + 2);
        if(total == 0){
            pageDataDto.setData(Collections.emptyList());
            log.info("项目配置批量查询configQueryDto:[{}], 结果:{}", configQueryDto, pageDataDto);
            return pageDataDto;
        }

        RowBounds rowBounds = new RowBounds((configQueryDto.getPageNow() - 1) * configQueryDto.getPageSize(), configQueryDto.getPageSize());
        List<Config> configList = extConfigMapper.selectByExample(configExample, rowBounds);
        pageDataDto.setData(BeanConverterUtil.convertToBeanList(configList, ConfigDto.class));
        log.info("项目配置批量查询configQueryDto:[{}], 结果:{}", configQueryDto, pageDataDto);
        return pageDataDto;
    }
}
